/**
 * https://leetcode.cn/problems/binary-tree-maximum-path-sum/submissions/583867166/
 * 124. 二叉树中的最大路径和
 * difficulty 陈贝纯 2024.11.29
 * 换根dp
 */

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int m=-1001;
    int dfs(TreeNode* root){
        if(root==nullptr)
        return 0;
        int l=dfs(root->left);
        if(l<0)
        l=0;
        int r=dfs(root->right);
        if(r<0)
        r=0;
        m=max(m,l+r+root->val);
        return max(l+root->val,r+root->val);
    }
    int maxPathSum(TreeNode* root) {
        dfs(root);
        return m;
    }
};